import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'

declare var $: any
@Component({
  selector: 'sa-outsource-processing-apply',
  templateUrl: './outsource-processing-apply.component.html'
})
export class OutsourceProcessingApplyComponent implements OnInit {
  validatorOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      deliveryDate: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择交货日期'
          }
        }
      },
      supplierName: {
        validators: {
          notEmpty: {
            message: '请输入供应商'
          }
        }
      },
      materialNumber: {
        validators: {
          notEmpty: {
            message: '请输入物料编码'
          }
        }
      },
      materialName: {
        validators: {
          notEmpty: {
            message: '请输入物料名称'
          }
        }
      },
      specification: {
        validators: {
          notEmpty: {
            message: '请输入规格型号'
          }
        }
      },
      count: {
        validators: {
          notEmpty: {
            message: '请输入数量'
          }
        }
      },
      units: {
        validators: {
          notEmpty: {
            message: '请输入单位'
          }
        }
      }
    }
  }
  fromType: any = ''
  tableData = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  searchKey: string = '' //搜索keyword
  startTime: string = ''
  endTime: string = ''
  addPermission: boolean = false
  delPermission: boolean = false
  editPermission: boolean = false

  tableSearch: any = {
    supplierName: '', //供应商
    materialNumber: '', //物料编码
    materialName: '' //物料名称
  }
  IncomingInspectReportForm: any = {
    id: '',
    supplierName: '', //供应商
    deliveryDate: '', //交货日期
    materialNumber: '', //物料编码
    materialName: '', //物料名称
    specification: '', //规格型号
    count: '', //数量
    units: '', //单位
    createTime: '', //创建时间
    createName: '' //创建人
  }

  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {})
  }

  ngOnInit() {
    this.initBtn()
    this.initDate().then(() => {
      this.load()
    })
  }
  //初始化权限按钮
  initBtn() {
    const btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_supplyChain:opApply')))
    console.log(btnData)
    if (!btnData) {
      return
    }
    for (let item of btnData) {
      if (item.sourceKey === 'opApply:addBtn' && item.parentId) {
        this.addPermission = true
      }
      if (item.sourceKey === 'opApply:delBtn' && item.parentId) {
        this.delPermission = true
      }
      if (item.sourceKey === 'opApply:editBtn' && item.parentId) {
        this.editPermission = true
      }
    }
  }

  //删除所选时间
  del_date() {
    this.startTime = ''
    this.endTime = ''
    $('#datetimepicker1').val('').change()
    $('#datetimepicker2').val('').change()
    $('#datetimepicker2').datetimepicker('setStartDate', null)
    $('#datetimepicker1').datetimepicker('setEndDate', null)
  }
  //table刷新
  refresh() {
    this.load()
  }
  //表格搜索
  table_search() {
    this.curPage = 1
    // this.searchKey = common.stringTrim(this.searchKey);
    this.load()
  }
  //初始化加载list数据
  load() {
    this.startTime = $('#datetimepicker1').val()
    this.endTime = $('#datetimepicker2').val()
    const data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        startTime: this.startTime,
        endTime: this.endTime,
        ...this.tableSearch
      }
    }
    const reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('dtsConsignorExtraWorkApply/page.html', reqdata).subscribe(result => {
      if (result.isSuccess) {
        this.tableData = result.exhibitDatas || []
        this.totalCount = result.recordCount
      }
    })
  }
  //初始化时间
  initDate() {
    var that = this
    return new Promise(function (resolve, reject) {
      System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
        System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
          $('#datetimepicker1')
            .datetimepicker({
              format: 'yyyy-mm-dd',
              language: 'zh-CN',
              autoclose: true,
              minView: 2
            })
            .on('changeDate', function (e) {
              var date = e.date
              var time = common.getTimeDay(date)
              that.startTime = time
              $('#datetimepicker2').datetimepicker('setStartDate', time)
            })
          $('#datetimepicker2')
            .datetimepicker({
              format: 'yyyy-mm-dd',
              language: 'zh-CN',
              autoclose: true,
              minView: 2
            })
            .on('changeDate', function (e) {
              var date = e.date
              var time = common.getTimeDay(date)
              that.endTime = time
              $('#datetimepicker1').datetimepicker('setEndDate', time)
            })
          $('#deliveryDateAdd')
            .datetimepicker({
              format: 'yyyy-mm-dd',
              language: 'zh-CN',
              autoclose: true,
              minView: 2
            })
            .on('changeDate', function (e) {
              var date = e.date
              var time = common.getTimeDay(date)
              that.IncomingInspectReportForm.deliveryDate = time
            })
          resolve(null)
        })
      })
    })
  }
  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  deleteRow(row) {
    this.jsonApiService.confirm_message('删除该条委外加工申请，确认要删除?').then(() => {
      const reqdata = 'id=' + row.id
      this.jsonApiService.http('dtsConsignorExtraWorkApply/deleteById.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }

  // 导出
  dataExceport() {
    this.startTime = $('#datetimepicker1').val()
    this.endTime = $('#datetimepicker2').val()

    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        startTime: this.startTime,
        endTime: this.endTime,
        export: 1,
        ...this.tableSearch
      }
    }

    common.exprotDataFile(data, 'gridPager', config.BaseURL + 'dtsConsignorExtraWorkApply/page.html')
  }

  //新建
  new_outsourceProcessing() {
    console.log(2231)
    this.router.navigate(['/supply-chain/outsource-processing-apply/outsource-processing-page'], {
      queryParams: {
        type: 'new'
      }
    })
  }
  //编辑页面
  updata_outsourceProcessing(row, modal) {
    this.resetForm()
    for (let key in this.IncomingInspectReportForm) {
      this.IncomingInspectReportForm[key] = row[key]
    }
    modal.show()
  }
  /*
   * form提交
   */
  apiControlSubmit(modal) {
    $('#IncomingInspectReportForm').bootstrapValidator('validate') //开启验证
    let isValid = $('#IncomingInspectReportForm').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      const formData = JSON.parse(JSON.stringify(this.IncomingInspectReportForm))
      console.log(this.IncomingInspectReportForm, formData)
      const reqdata = { data: JSON.stringify(formData) }
      this.jsonApiService.http_obj('dtsConsignorExtraWorkApply/edit.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
          this.modalClose(modal)
        }
      })
    }
  }
  /*
   * 关闭弹窗
   */
  modalClose(modal) {
    modal.hide()
  }
  resetForm() {
    $('#IncomingInspectReportForm').data('bootstrapValidator').resetForm()
    let nowTime = new Date().toLocaleDateString().replace(/\//g, '-')
    this.IncomingInspectReportForm = {
      id: '',
      supplierName: '', //供应商
      deliveryDate: '', //交货日期
      materialNumber: '', //物料编码
      materialName: '', //物料名称
      specification: '', //规格型号
      count: '', //数量
      units: '', //单位
      createTime: '', //创建时间
      createName: '' //创建人
    }
  }
  // 删除输入
  delKey(type) {
    this.tableSearch[type] = ''
  }
}
